package com.dev.utils;

import com.dev.receiver.PackageSubscriber;
import ohos.aafwk.ability.AbilitySlice;
import ohos.event.commonevent.CommonEventManager;
import ohos.event.commonevent.CommonEventSubscribeInfo;
import ohos.event.commonevent.MatchingSkills;
import ohos.rpc.RemoteException;

/**
 * 监听应用安装、更新、卸载的工具类
 */
public class PackageUtils {

    /**
     * 初始化应用监听过滤器
     *
     * @param slice
     * @return
     */
    public static PackageSubscriber initMatch(AbilitySlice slice) {
        MatchingSkills match = new MatchingSkills();
        match.addEvent(PackageSubscriber.COMMON_EVENT_PACKAGE_ADDED);
        match.addEvent(PackageSubscriber.COMMON_EVENT_PACKAGE_REMOVED);
        match.addEvent(PackageSubscriber.COMMON_EVENT_PACKAGE_REPLACED);
        CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(match);
        subscribeInfo.setPriority(100);
        PackageSubscriber subscriber = new PackageSubscriber(subscribeInfo, slice);
        return subscriber;
    }

    /**
     * 订阅应用改变事件
     *
     * @param subscriber
     */
    public static void subscriberPackage(PackageSubscriber subscriber) {
        try {
            CommonEventManager.subscribeCommonEvent(subscriber);
        } catch (RemoteException e) {
            LogUtils.warn("PACKAGE", "subscribe in package events failed!");
        }
    }

    /**
     * 取消订阅应用改变事件
     */
    public static void unSubscribePackage(PackageSubscriber subscriber) {
        try {
            CommonEventManager.unsubscribeCommonEvent(subscriber);
        } catch (RemoteException e) {
            LogUtils.warn("PACKAGE", "unsubscribe in package events failed!");
        }
    }
}
